import { Vue } from 'vue-class-component'
import router from '@/router'
import store from '@/store'
import { ElMessage } from 'element-plus'

interface ILoginParams {
  username: string
  password: string
}

export default class login extends Vue {
  loading = false
  loginParams: ILoginParams = {
    username: '',
    password: ''
  }

  login (): void {
    if (this.loginParams.username === '') {
      ElMessage.warning({
        message: '请输入用户名',
        type: 'warning'
      })
    } else if (this.loginParams.username.length > 11) {
      ElMessage.warning({
        message: '用户名不存在',
        type: 'warning'
      })
    } else if (this.loginParams.password === '') {
      ElMessage.warning({
        message: '请输入密码',
        type: 'warning'
      })
    } else if (this.loginParams.password.length > 11) {
      ElMessage.warning({
        message: '密码错误',
        type: 'warning'
      })
    } else {
      this.loading = true
      store.dispatch('login', this.loginParams)
        .then(response => {
          console.log('connect success')
          this.loading = false
          const code = response.data.code
          if (code === 200) {
            ElMessage.success('登录成功!')
            const data = response.data.data
            const token = data.token
            const user = data.user
            const isAdmin = data.isAdmin
            store.commit('SET_TOKEN', token)
            store.commit('SET_USER', user)
            store.commit('SET_ADMIN', isAdmin)
            router.push({
              path: '/home',
              query: { data: response.data.data }
            })
          } else {
            ElMessage.error('账号或密码错误')
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
          console.log('connect failed')
        })
    }
  }

  register (): void {
    router.push({
      path: '/register'
    })
  }
}
